/*
 * @Author: yangzonglong
 * @Date: 2021-09-01 16:14:02
 * @version: v1.0.0
 * @Descripttion: view util
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-09-01 16:34:02
 * @Auditor: 
 */
import { ActionFieldType, ControlProps } from './../interface';

export const handTableColumnRelation = (controlId: string, editFields: string[]) => {
  const columnsField: string[] = [];

  editFields.forEach(field => {
    const arr = field.split('#');

    // 找出相关联的
    if (arr.length === 2 && arr[0] === controlId) {
      columnsField.push(arr[1])
    }
  })

  return columnsField
}

export function includesControl(arr: string[], item: ControlProps) {
  const options: any = item.options;

  if (arr.includes(item.id)
    || arr.includes(options.formItemProps?.name)
    || arr?.includes(options.name)
    || arr.includes('*')
    ) {
      return true
    }
}

export function getActionFiled(actionFiled: ActionFieldType, item: ControlProps) {
  const options: any = item.options;

  let obj = actionFiled[item.id] 
    || actionFiled[options.formItemProps?.name] 
    || actionFiled[options.name] 
    || {};

  if(item.sourceForm && actionFiled[item.sourceForm]) {
    obj = {...actionFiled[item.sourceForm], ...obj}
  }

  const mergeObj = { ...actionFiled['*'], ...obj };

  const excludeMyself = (key: string) => {
    if(mergeObj[key]) {
      mergeObj[key] = mergeObj[key].filter((k: string) => {
        return k !== item.id && k !== options.formItemProps?.name && k !== options.name
      })
    }
  }

  // 如果配置了具体控件，需要去除和key同名的，防止如下情况
  // load next({}, { *: { hide: true, hideExcludes: ['a'] } })
  // change next({}, { a: { hide: false } })
  // 此时会合并为 { hide: false, hideExcludes: ['a'] }，a将不显示，其实用户是期望显示
  if(Object.keys(obj).length) {
    excludeMyself('hideExcludes');
    excludeMyself('disabledExcludes');
    excludeMyself('requiredExcludes');
  }

  return mergeObj
}

export function tableIdToName(id: string, list: ControlProps[]) {
  const isColumn = id.includes('#');
  if(!isColumn) return id;
  
  const arr = id.split('#');
  const _id = isColumn ? id.split('#')[0] : id;

  const curr = list.find(item => item.id === _id && item.type === 'table');

  // table组件
  if(curr) {
    if(isColumn) {
      return curr.options?.name + '#' + arr[1]
    }else {
      return curr.name;
    }
  }

  return id;
}